package com.settlement.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.model.entity.SysFlowMarketHistory;
import com.settlement.system.service.SysFlowMarketHistoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.settlement.system.model.query.SysFlowMarketHistoryQuery;
import com.settlement.system.model.form.SysFlowMarketHistoryForm;
import org.springdoc.core.annotations.ParameterObject;
import io.swagger.v3.oas.annotations.Parameter;
import com.settlement.system.model.vo.SysFlowMarketHistoryImportVo;
import com.settlement.system.listener.easyexcel.SysFlowMarketHistoryListener;
import com.alibaba.excel.EasyExcel;

import com.alibaba.excel.EasyExcelFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 流程市场历史版本表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-01-08
 */
@RestController
@RequestMapping("/api/v1/flowMarketHistory")
@RequiredArgsConstructor
public class SysFlowMarketHistoryController {

    private final SysFlowMarketHistoryService sysFlowMarketHistoryService;

    @Operation(summary = "流程市场历史版本表分页", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysFlowMarketHistory> getPage(@ParameterObject SysFlowMarketHistoryQuery queryParams) {
        Page<SysFlowMarketHistory> result = sysFlowMarketHistoryService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存流程市场历史版本表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:flowMarketHistory:save')")
    public Result<?> saveSysFlowMarketHistory(@RequestBody @Valid SysFlowMarketHistoryForm sysFlowMarketHistoryForm) {
        boolean result = sysFlowMarketHistoryService.saveSysFlowMarketHistory(sysFlowMarketHistoryForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取流程市场历史版本表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysFlowMarketHistoryForm> getSysFlowMarketHistoryFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysFlowMarketHistoryForm sysFlowMarketHistory = sysFlowMarketHistoryService.getSysFlowMarketHistoryFormData(id);
        return Result.success(sysFlowMarketHistory);
    }

    @Operation(summary = "根据脚本ID获取历史版本", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/getHistoryList/{flowId}")
    public Result<?> getHistoryList(@PathVariable String flowId) {
        List<SysFlowMarketHistory> histories = sysFlowMarketHistoryService.getHistoryList(flowId);
        return Result.success(histories);
    }

    @Operation(summary = "回滚历史版本", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/rollBack/{flowId}/{historyId}")
    public Result<?> rollBack(@PathVariable String flowId, @PathVariable String historyId) {
        boolean result = sysFlowMarketHistoryService.rollBack(flowId, historyId);
        return Result.judge(result);
    }

    @Operation(summary = "删除流程市场历史版本表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:flowMarketHistory:delete')")
    public Result<?> deleteSysFlowMarketHistory(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysFlowMarketHistoryService.deleteSysFlowMarketHistory(ids);
        return Result.judge(result);
    }

    @Operation(summary = "流程市场历史版本表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysFlowMarketHistoryImport")
    @PreAuthorize("@ss.hasPerm('sys:flowMarketHistory:import')")
    @PreventDuplicateSubmit
    public Result<?> sysFlowMarketHistoryImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysFlowMarketHistoryListener listener = new SysFlowMarketHistoryListener();
        EasyExcelFactory.read(file.getInputStream(), SysFlowMarketHistoryImportVo.class, listener).sheet(0).doRead();
        List<SysFlowMarketHistoryImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysFlowMarketHistoryService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出流程市场历史版本表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:flowMarketHistory:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "流程市场历史版本表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysFlowMarketHistoryImportVo> sysFlowMarketHistoryList = sysFlowMarketHistoryService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysFlowMarketHistoryImportVo.class).sheet("流程市场历史版本表").doWrite(sysFlowMarketHistoryList);
    }
}

